package com.ogawa.project2213n.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.Group
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.ogawa.base.constants.Constants
import com.ogawa.base.mqtt.MqttManager
import com.ogawa.base.utils.SpUtil
import com.ogawa.projectcommon.widget.LevelView
 import com.ogawa.project2213N.base.Base2213NMqttActivity
import com.ogawa.project2213n.R
import com.ogawa.project2213n.bean.Massage2213NArmchair
import com.ogawa.projectcommon.constants.UrlPathConstant
import com.ogawa.projectcommon.widget.TimeView

@Route(path = UrlPathConstant.ACTIVITY_2213N_DEVICE_MAIN)
class Device2213nMainActivity : Base2213NMqttActivity(), View.OnClickListener {
    private lateinit var tvAuto: TextView
    private lateinit var tvAdvance: TextView
    private lateinit var tvHealthLife: TextView
    private lateinit var tvPower: TextView
    private lateinit var tvPause: TextView
    private lateinit var tvCurrentPro: TextView
    private lateinit var tvRemainTime: TextView
    private lateinit var lv3D: LevelView
    private lateinit var lvStrength: LevelView
    private lateinit var lvSpeed: LevelView
    private lateinit var lvGas: LevelView
    private lateinit var tvFootRoll: TextView
    private lateinit var tvHeat: TextView
    private lateinit var tvShake: TextView
    private lateinit var ivPoint: ImageView
    private lateinit var ivGasShoulder: ImageView
    private lateinit var ivGasHand: ImageView
    private lateinit var ivGasFoot: ImageView
    private lateinit var ivHeat: ImageView
    private lateinit var ivFootRoll: ImageView
    private lateinit var timeView: TimeView
    private lateinit var groupGasLeg: Group
    private lateinit var groupShake: Group
    private var pointRes = arrayOf(
        R.drawable.img_poing_16,
        R.drawable.img_poing_15,
        R.drawable.img_poing_14,
        R.drawable.img_poing_13,
        R.drawable.img_poing_12,
        R.drawable.img_poing_11,
        R.drawable.img_poing_10,
        R.drawable.img_poing_9,
        R.drawable.img_poing_8,
        R.drawable.img_poing_7,
        R.drawable.img_poing_6,
        R.drawable.img_poing_5,
        R.drawable.img_poing_4,
        R.drawable.img_poing_3,
        R.drawable.img_poing_2,
        R.drawable.img_poing_1
    )

    companion object {
        const val AUTO = 1
        const val MANUAL_MODEL = 2
        const val ADVANCE = 3
        var failTimes = 0
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_device_main
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun initView() {
        super.initView()
        setTitle(getString(R.string.current_chair))
        setRightImg(R.drawable.user_img_gray_head_empty)
        setAddOnclick(View.OnClickListener {
            ARouter.getInstance().build(UrlPathConstant.ACTIVITY_USER_INFO).navigation()
        })
        tvAuto = findViewById(R.id.tv_auto)
        tvAuto.setOnClickListener(this)
        tvAdvance = findViewById(R.id.tv_advance)
        tvAdvance.setOnClickListener(this)
        tvHealthLife = findViewById(R.id.tv_health_life)
        tvHealthLife.setOnClickListener(this)
        tvPower = findViewById(R.id.tv_power)
        tvPower.setOnClickListener(this)
        tvPause = findViewById(R.id.tv_pause)
        tvPause.setOnClickListener(this)
        tvCurrentPro = findViewById(R.id.tv_current_program)
        tvRemainTime = findViewById(R.id.tv_remain_time)
        findViewById<TextView>(R.id.tv_seat_adjust).setOnClickListener(this)
        findViewById<ImageView>(R.id.iv_wifi_bg).setOnClickListener(this)
        lv3D = findViewById(R.id.lev_view_3d)
        lvStrength = findViewById(R.id.lev_view_strength)
        lvStrength.setFunc(Constants.MASSAGE_STRENGTH)
        lvSpeed = findViewById(R.id.lev_view_speed)
        lvSpeed.setFunc(Constants.MASSAGE_SPEED)
        lvGas = findViewById(R.id.lev_view_gas)
        lvGas.setFunc(Constants.AIR_INTENSITY_ADJUST)
        tvFootRoll = findViewById(R.id.tv_foot_roll)
        tvFootRoll.setOnClickListener(this)
        tvHeat = findViewById(R.id.tv_heat)
        tvHeat.setOnClickListener(this)
        tvShake = findViewById(R.id.tv_shake)
        tvShake.setOnClickListener(this)
        ivPoint = findViewById(R.id.iv_point)
        ivGasShoulder = findViewById(R.id.iv_gas_shoulder)
        ivGasHand = findViewById(R.id.iv_gas_arm)
        ivGasFoot = findViewById(R.id.iv_gas_foot)
        groupGasLeg = findViewById(R.id.group_gas_leg)
        groupShake = findViewById(R.id.group_shake)
        ivHeat = findViewById(R.id.iv_heat)
        ivFootRoll = findViewById(R.id.iv_foot_roll)
        timeView = findViewById(R.id.time_view)
    }


    override fun onClick(v: View?) {
        if (!IS_PROJECT_2213N_TEST && !isSnExist()) {
            return
        }

        when (v?.id) {
            R.id.tv_auto -> startActivityForResult(
                Intent(this, AutoActivity::class.java),
                AUTO
            )
            R.id.tv_seat_adjust -> startActivity(Intent(this, Device2213nSeatAdjustActivity::class.java))
            R.id.tv_advance -> startActivityForResult(
                Intent(this, Device2213nAdvanceActivity::class.java),
                ADVANCE
            )
            R.id.tv_health_life -> startActivityForResult(
                Intent(
                    this,
                    Device2213nManualModeActivity::class.java
                ), MANUAL_MODEL
            )
//            R.id.iv_wifi_bg -> startActivity(Intent(this, StartNetActivity::class.java))
            R.id.tv_power -> {
                if (tvPower.isSelected) {
                    publish(Constants.RUNNING_STATUS, "0")
                } else {
                    if (Massage2213NArmchair.getInstance().reset == 1) {
                        publish(Constants.RUNNING_STATUS, "1")
                    } else {
                        ToastUtils.showShort( getString(R.string.movement_resetting_tip))
                    }
                }
            }
            R.id.tv_pause -> {
                if (tvPause.isSelected) {
                    publish(Constants.RUNNING_STATUS, "3")
                } else {
                    publish(Constants.RUNNING_STATUS, "2")
                }
            }
            R.id.tv_foot_roll -> publish(Constants.FOOT_WHEEL, "3")
            R.id.tv_heat -> publish(Constants.HEAT_BACK, "3")
            R.id.tv_shake -> publish(Constants.SIT_VIBRATE_BUTTON, "3")
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onDeviceStateChange() {
        super.onDeviceStateChange()
        val instance = Massage2213NArmchair.getInstance()
        tvPower.isSelected = instance.runningStatus == 1 || instance.runningStatus == 2
        tvPause.isSelected = instance.runningStatus == 2 || instance.runningStatus == 6
        tvPause.text =
            if (tvPause.isSelected) getString(R.string.start) else getString(R.string.pause)
        val deviceStatusBean = instance.deviceStatusBean
        if (deviceStatusBean != null) {
            val autoProgram = deviceStatusBean.functions.autoProgram
            val autoValue = Integer.parseInt(autoProgram.modelValue)
            tvAuto.isSelected = autoValue != 0
            if (autoValue > 0) {
                tvCurrentPro.text = getString(R.string.current_program) + autoProgram.itemName
            }
            val healthProgram = deviceStatusBean.functions.lifeAutoProgram
            val healthValue = Integer.parseInt(healthProgram.modelValue)
            tvHealthLife.isSelected = healthValue != 0
            if (healthValue > 0) {
                tvCurrentPro.text = getString(R.string.current_program) + healthProgram.itemName
            }
            val advanceProgram = deviceStatusBean.functions.advanceAutoProgram
            val advanceValue = advanceProgram.modelValue
            tvAdvance.isSelected = advanceValue != "0"
            if (tvAdvance.isSelected) {
                tvCurrentPro.text =
                    getString(R.string.current_program) + getString(R.string.advance_massage)
            }
            if (autoValue == 0 && healthValue == 0 && advanceValue == "0") {//无程序运行
                tvCurrentPro.text = getString(R.string.current_program)
            }
            val min = deviceStatusBean.functions.timeMin.modelValue
            var sec = deviceStatusBean.functions.timeSec.modelValue
            if (sec.length < 2) {
                sec = "0$sec"
            }
            tvRemainTime.text = getString(R.string.remain_time) + min +getString(R.string.minute)
            lvStrength.setLev(Integer.parseInt(deviceStatusBean.functions.massageStrength.modelValue))
            lvSpeed.setLev(Integer.parseInt(deviceStatusBean.functions.massageSpeed.modelValue))
            lvGas.setLev(Integer.parseInt(deviceStatusBean.functions.airIntensity.modelValue))
            timeView.setTime(Integer.parseInt(deviceStatusBean.functions.timeMin.modelValue))
            tvHeat.isSelected =
                Integer.parseInt(deviceStatusBean.functions.heatBack.modelValue) == 1
            tvFootRoll.isSelected =
                Integer.parseInt(deviceStatusBean.functions.footWheel.modelValue) == 1
            tvShake.isSelected =
                Integer.parseInt(deviceStatusBean.functions.sitVibrateButton.modelValue) == 1
            ivGasShoulder.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.airCellShoulderStatus.modelValue) == 1) View.VISIBLE else View.GONE
            ivGasHand.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.airCellHandStatus.modelValue) == 1) View.VISIBLE else View.GONE
            ivGasFoot.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.airCellFootStatus.modelValue) == 1) View.VISIBLE else View.GONE
            groupGasLeg.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.airCelllegStatus.modelValue) == 1) View.VISIBLE else View.GONE
//            groupShake.visibility =
//                if (Integer.parseInt(deviceStatusBean.functions.sitVibrateButton.modelValue) == 1) View.VISIBLE else View.GONE
            ivHeat.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.heatBack.modelValue) == 1) View.VISIBLE else View.GONE
            ivFootRoll.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.footWheel.modelValue) == 1) View.VISIBLE else View.GONE
            ivPoint.setImageResource(pointRes[Integer.parseInt(deviceStatusBean.functions.yPos.modelValue)])

        } else {
            tvAuto.isSelected = false
            tvAdvance.isSelected = false
            tvHealthLife.isSelected = false
            tvCurrentPro.text = getString(R.string.current_program)
            tvRemainTime.text = getString(R.string.remain_time)
            lvStrength.setLev(-1)
            lvSpeed.setLev(-1)
            lvGas.setLev(-1)
            timeView.setTime(-1)
            tvHeat.isSelected = false
            tvFootRoll.isSelected = false
            tvShake.isSelected = false
            ivGasShoulder.visibility = View.GONE
            ivGasHand.visibility = View.GONE
            ivGasFoot.visibility = View.GONE
            groupGasLeg.visibility = View.GONE
            groupShake.visibility = View.GONE
            ivHeat.visibility = View.GONE
            ivFootRoll.visibility = View.GONE
            ivPoint.setImageResource(0)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val program = data?.getStringExtra("program")
        when (requestCode) {
            AUTO -> {
                if (program != null && program.isNotEmpty()) {
                    publish(Constants.AUTO_PROGRAM, program)
                }
            }
            MANUAL_MODEL -> {
                if (program != null && program.isNotEmpty()) {
                    publish(Constants.LIFE_AUTO_PROGRAM, program)
                }
            }
            ADVANCE -> {
                if (program != null && program.isNotEmpty()) {
                    publish(Constants.ADVANCE_AUTO_PROGRAM, "1", program)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        MqttManager.getInstance().disconnect()
        SpUtil.set(SpUtil.IS_NEED_RE_CONNECT_MQTT, false)
    }

}